package com.xlz.service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import com.xlz.domain.AppWorker;
import com.xlz.worker.Worker;
import com.xlz.domain.AppTask;

/**
 * 应用工作者实例信息CRUD工具类.
 * @author 张蕾蕾
 * @date 2018 03 24
 */
public class AppWorkerService extends BaseJdbcService<AppWorker>{

	public AppWorkerService(DataSource dataSource) {
		super(dataSource);
	}

	public int [] insertBatch(List<AppWorker> list)  {
		int[] count = null;
		Connection connection = null ;
		PreparedStatement pstmt = null;
		String sql = "INSERT app_worker("
				+    "task_id,register_instance_id,register_worker,create_time,update_time,shard_item,app_no,active"
				+ 	 ")VALUES(?,?,?,now(),now(),?,?,1)";
		try {
			connection = getDataSource().getConnection();
			pstmt = connection.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE,
					ResultSet.CONCUR_READ_ONLY);
			for (AppWorker appWorker : list) {
				if(appWorker.getShardItem() != null && !"".equals(appWorker.getShardItem())){
					pstmt.setLong(1, appWorker.getTaskId());
					pstmt.setString(2, appWorker.getRegisterInstanceId());
					pstmt.setString(3, appWorker.getRegisterWorker());
					pstmt.setString(4, appWorker.getShardItem() == null ? "no_shard" : appWorker.getShardItem());
					pstmt.setString(5, appWorker.getAppNo());
					pstmt.addBatch();
				}
			}
			count = pstmt.executeBatch();
			connection.commit();
		} catch (SQLException e) {
			if(connection != null)
				try {
					connection.rollback();
				} catch (SQLException e1) {
					LOG.error("执行sql回滚时存在异常",sql,e1);
				}
			LOG.error("执行sql存在异常",sql,e);
		}finally{
			closeResources( connection,  pstmt);
		}
		return count;
	}

	public List<AppWorker> getAllByTaskId(Long taskId,String instanceId){
		String sql = "select id,task_id,register_instance_id,register_worker,create_time,shard_item,load_time,execute_time,load_total,wait_deal_total "
				+ 	 "from app_worker "
				+ 	 "where active=1 ";
				if(taskId != null)
					sql+= 	 "and task_id="+taskId ;
				if(instanceId != null)
					sql +=    " and register_instance_id='"+instanceId+"' ";
		return findAll(sql, AppWorker.class);
	}
	
	public int[] batchUpdateByWorker(Map<Long, Worker> taskWorkerPool) throws SQLException{
		int[] count = null;
		if(taskWorkerPool.size() == 0){
			return count;
		}
		StringBuffer keys = new StringBuffer();
		for(Map.Entry<Long, Worker> entry : taskWorkerPool.entrySet()){
			keys.append(",").append(entry.getKey());
		}
		keys.delete(0, 1);
		String sql = "update app_worker set update_time=now() where id in ("+keys.toString()+")";
		executeUpdate(sql);
		return count;
	}

	public boolean deleteByRegisterInstanceId(String registerInstanceId) throws SQLException {
		List<AppWorker> list = getAllByTaskId(null,registerInstanceId);
		for(AppWorker entity : list){
			deleteById(entity.getId());
		}
		return true;
	}

	public boolean deleteById(Long id) throws SQLException {
		String sql = "delete from app_worker where id="+id;
		return  executeUpdate(sql) > 0;
	}
	
	public int findCount(AppTask entity) {
		String sql = "select count(1) from app_worker where active=1 and task_id="+entity.getId();// + " and update_time > date_add(now(), interval -"+entity.getDeadTime()+" microsecond)"  ;
		try {
			return findCount(sql);
		} catch (Exception e) {
			return -1;
		}
	}
	@Override
	public String getNamespace() {
		return "com.xlz.pojo.AppWorker.";
	}
}
